package com.gzs.learn.admin.config;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.gzs.learn.admin.common.constant.AdminConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;


/**
 * @author guanzhisong
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
    private static final String[] BASE_PACKAGES = new String[] {
            AdminConstants.SYSTEM_PREFIX + ".serial.controller.api",
            AdminConstants.SYSTEM_PREFIX + ".web.controller.api",
            AdminConstants.SYSTEM_PREFIX + ".log.controller.api"
            };

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2).apiInfo(new ApiInfoBuilder()
                // .title("swagger-bootstrap-ui-demo RESTful APIs")
                .description("").termsOfServiceUrl("http://www.xx.com/")
                .contact(new Contact("guanzhisong", "", "guanzhisong@gmail.com")).version("1.0").build())
                // 分组名称
                .groupName("2.X版本").select()
                // 这里指定Controller扫描包路径
                // .apis(RequestHandlerSelectors.basePackage(Constants.SYSTEM_PREFIX + ".serial.controller.api"))
                .apis(basePackage(BASE_PACKAGES)).paths(PathSelectors.any()).build();
        return docket;
    }

    @SuppressWarnings("deprecation")
    public static Predicate<RequestHandler> basePackage(final String[] basePackage) {
        return input -> Optional.fromNullable(input.declaringClass()).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String[] basePackage) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }
}
